<template>
  <div class="field-library">
    <!-- 页面标题 -->
    <div class="page-title">字段库</div>

    <div
        class="category-container"
        v-for="category in categoryList"
        :key="category.id"
    >
      <div class="category-title">{{ category.name }}</div>
      <div class="field-list">
        <div
            class="field-item"
            v-for="field in category.fields"
            :key="field?.id"
            v-if="field"
        >
          <div class="field-content">
            <el-checkbox v-model="field.selected"></el-checkbox>
            <span class="field-name">{{ field.name }}</span>
            <span class="field-tags">
              <el-tag
                  size="mini"
                  :type="field.isMultiple ? 'success' : 'info'"
                  @click.stop="toggleMultiple(field)"
                  close-transition
                  effect="plain"
              >{{ field.isMultiple ? '多条' : '单条' }}</el-tag
              >
              <el-tag
                  size="mini"
                  :type="field.isRequired ? 'success' : 'info'"
                  @click.stop="toggleRequired(field)"
                  close-transition
                  effect="plain"
              >{{ field.isRequired ? '必须' : '可选' }}</el-tag
              >
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="footer-buttons">
      <el-button
          type="primary"
          round
          @click="submitForm"
          :loading="submitLoading"
      >确定</el-button
      >
      <el-button round @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script>
import axios from "@/utils/request";
import { useRoute, useRouter } from "vue-router";

export default {
  setup() {
    const route = useRoute();
    const router = useRouter();
    return { route, router };
  },
  data() {
    return {
      categoryList: [],
      templateId: this.$route.query.templateId,
      submitLoading: false,
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      try {
        const response = await axios.get(
            "/admin/template/material-categories-with-fields"
        );
        if (response.code === 1) {
          console.log(response.data);
          this.categoryList = response.data.map((category) => ({
            ...category,
            fields: category.fields
                ? category.fields.map((field) => ({
                  ...field,
                  selected: false,
                  isMultiple: field?.isMultiple || false,
                  isRequired: field?.isMust || false,
                }))
                : [],
          }));
        } else {
          this.$message.error(response.msg || "获取字段列表失败");
        }
      } catch (error) {
        this.$message.error(error.message || "请求出错");
      }
    },
    toggleMultiple(field) {
      field.isMultiple = !field.isMultiple;
    },
    toggleRequired(field) {
      field.isRequired = !field.isRequired;
    },
    async submitForm() {
      try {
        this.submitLoading = true;

        // 收集选中的材料类目ID和字段ID
        const selectedCategoryIds = [];
        const selectedFieldIds = [];
        for (const category of this.categoryList) {
          if (category.fields && category.fields.length > 0) {
            const selectedFields = category.fields.filter(
                (field) => field.selected
            );
            if (selectedFields.length > 0) {
              selectedCategoryIds.push(category.id);
              selectedFields.forEach((field) => selectedFieldIds.push(field.id));
            }
          }
        }

        // 构建请求体
        const fieldSelectionDTO = {
          categoryBaseIds: selectedCategoryIds,
          fieldIds: selectedFieldIds,
        };

        console.log(
            "Payload being sent to backend:",
            JSON.stringify(fieldSelectionDTO, null, 2)
        );

        // 发送请求
        // Use axios.post directly, which is cleaner
        const response = await axios.post(
            `/admin/template/saveTemplateFields`, // URL
            fieldSelectionDTO, // Data
            {
              params: {
                templateId: this.templateId,
              },
            } // Config
        );

        // Debug: Log the *entire* response object
        console.log("Full Axios response:", response);

        // Debug: Check the type of response
        console.log("Type of response:", typeof response);

        // Debug: Check the properties of the response object
        console.log("Keys in response:", Object.keys(response));

        // Debug: Check if response.code exists and its value/type
        console.log("response.code exists:", 'code' in response);
        if('code' in response){
          console.log("response.code value:", response.code);
          console.log("typeof response.code:", typeof response.code);
        }

        // Debug: Check if response.msg exists
        console.log("response.msg exists:", 'msg' in response);

        // Debug: Check the value of this.templateId just before the route push
        console.log("this.templateId before router push:", this.templateId);

        // Check if the response contains data property, and then check the code
        if (response && response.code === 1) {
          this.$message.success("字段保存成功");
          // Debug: Print the $router object to make sure it exists
          console.log('this.$router', this.$router);
          this.$router.push({
            name: "editTemplate",
            params: { id: this.templateId },
          });
        } else {
          this.$message.error(response.msg || "字段保存失败");
        }
      } catch (error) {
        this.$message.error("保存字段失败");
        // Log the full error object for detailed information.
        console.error("Error submitting form:", error);
      } finally {
        this.submitLoading = false;
      }
    },
    cancel() {
      this.$router.push({
        name: "editTemplate",
        params: { id: this.templateId },
      });
    },
  },
};
</script>

<style scoped>
.field-library {
  padding: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: left;
}

.category-container {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  border: 2px solid #cccccc;
  box-shadow: none;
}

.category-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: left;
  color: #666666;
}

.field-list {
  display: flex;
  flex-wrap: wrap;
}

.field-item {
  display: flex;
  margin-right: 30px;
  margin-bottom: 15px;
  width: 300px;
}

.field-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction: row;
  padding: 10px;
  border: 1px solid #cccccc;
  border-radius: 5px;
  width: 100%;
}

.field-name {
  color: #666666;
  margin-left: 10px;
}

.field-tags {
  margin-left: 5px;
  display: flex;
  align-items: center;
}

.el-checkbox {
  order: -1;
  color: #666666;
  margin-right: 5px;
}

/* 覆盖element ui 样式，实现内边距*/
.el-checkbox ::v-deep .el-checkbox__label {
  padding-left: 5px;
}

.footer-buttons {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.footer-buttons .el-button {
  margin: 0 10px;
}

/* 自定义 el-tag 样式 */
.el-tag {
  cursor: pointer;
  border: 1px solid #cccccc;
  background-color: transparent;
  color: #666666;
}

.el-tag--info {
  background-color: transparent;
  color: #999999;
  border-color: #cccccc;
}

/* 选中状态的文字颜色 */
.el-tag--success {
  color: #67c23a;
}
</style>